import style from "./index.module.scss";
import {
  Layout,
  Button,
  Form,
  Input,
  Flex,
  Space,
  Row,
  Col,
  message,
} from "antd";
import type { FormProps, FormInstance } from "antd";
// import Dentify from "@/component/dentify";
// import type { DentifyHandle } from "@/component/dentify";
import Dentify, { type DentifyHandle } from "react_dentify";
import { useEffect, useRef, useState } from "react";
import Validate from "self_format";
import { get } from "@/api";
import { generateToken, setCookieWithExpiry } from "@/utils/generateToken";
import { useNavigate } from "react-router-dom";
export default function Login() {
  const navigate = useNavigate();
  const [form]: [FormInstance] = Form.useForm();
  type FieldType = {
    phoneNumber?: string;
    dentify?: string;
  };
  const { Content, Footer } = Layout;
  const [messageApi, contextHolder] = message.useMessage();
  const [dentify, setDentify] = useState("");

  const updateForm = (newCode: string) => {
    setDentify(newCode);
  };
  const dentifyRef = useRef<DentifyHandle>(null); //验证码DOM
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    if (values.dentify?.toUpperCase() === dentify.toUpperCase()) {
      messageApi.open({
        type: "success",
        content: "登录成功",
      });
      const { token, expirationTime } = generateToken(
        form.getFieldValue("phoneNumber"),
        form.getFieldValue("dentify"),
        60 * 24
      );
      setCookieWithExpiry("auth_token", token, expirationTime);
      setCookieWithExpiry(
        "token_expiry",
        expirationTime.toString(),
        expirationTime
      );
      setCookieWithExpiry("auth_info", "已登录", expirationTime);
      navigate("/home");
    } else {
      messageApi.open({
        type: "error",
        content: "验证码错误",
      });
      if (dentifyRef.current) dentifyRef.current.drawPic();
    }
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  const [slogan, setSlogan] = useState("");
  //获取每日一语
  const getSlogan = async () => {
    const {
      data: { content },
    } = await get("https://api.xygeng.cn/one");
    setSlogan(content);
  };
  useEffect(() => {
    getSlogan();
  });
  return (
    <>
      {contextHolder}
      <Layout className={style.layout}>
        <Content className={style.content}>
          <Form
            className={style.loginForm}
            name="basic"
            labelCol={{ span: 6 }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
            form={form}
          >
            <Flex gap="large" vertical>
              <Form.Item>
                <div
                  style={{
                    fontSize: "20px",
                    color: "black",
                    fontWeight: "bold",
                    textAlign: "center",
                  }}
                >
                  登录
                </div>
              </Form.Item>

              <Space direction="vertical">
                <Form.Item<FieldType>
                  label="手机号"
                  name="phoneNumber"
                  validateTrigger="onBlur"
                  rules={[
                    { required: true, message: "请输入手机号" },
                    () => ({
                      validator(_, value) {
                        if (!value || Validate.mobileCheck(value)) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error("手机号格式错误!"));
                      },
                    }),
                  ]}
                >
                  <Input />
                </Form.Item>

                <Form.Item<FieldType>
                  label="验证码"
                  name="dentify"
                  validateTrigger="onBlur"
                  rules={[
                    { required: true, message: "请输入验证码" },
                    // () => ({
                    //   validator(_, value) {
                    //     if (
                    //       value.dentify?.toUpperCase() ===
                    //       dentify.current.toUpperCase()
                    //     ) {
                    //       return Promise.resolve();
                    //     }
                    //     return Promise.reject(new Error("验证码错误"));
                    //   },
                    // }),
                  ]}
                >
                  <Row gutter={8} style={{ position: "relative" }}>
                    <Col span={12}>
                      <Input />
                    </Col>
                    <Col span={12} style={{ position: "absolute", right: 0 }}>
                      <Dentify
                        ref={dentifyRef}
                        fontSizeMin={30}
                        fontSizeMax={30}
                        canvasWidth={100}
                        canvasHeight={50}
                        onUpdateForm={updateForm}
                      />
                    </Col>
                  </Row>
                </Form.Item>
              </Space>

              <Form.Item>
                <Button className={style.loginFormButton} htmlType="submit">
                  登录
                </Button>
              </Form.Item>
            </Flex>
          </Form>
        </Content>
        <Footer className={style.footer}>{slogan}</Footer>
      </Layout>
    </>
  );
}
